package com.zc.auth.security.core.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.zc.auth.security.core.exception.AnonymousAccessDeniedException;
import com.zc.commons.http.entity.Response;
import com.zc.commons.http.enums.RespCode;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class RoleAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException ex) throws IOException, ServletException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");
        RespCode respCode = RespCode.FORBIDDEN;
        // 禁止匿名访问  需要提示登录
        if (ex instanceof AnonymousAccessDeniedException) {
            respCode = RespCode.UNAUTHORIZED;
        }
        resp.setStatus(respCode.getCode());
        Response<String> respData = Response.error(respCode, ex.getMessage());
        String jsonString = JSON.toJSONString(respData, SerializerFeature.WriteMapNullValue);
        PrintWriter printWriter = resp.getWriter();
        printWriter.write(jsonString);
        if (printWriter != null) {
            printWriter.flush();
            printWriter.close();
        }
    }
}
